<?php

namespace app\admin\controller\basic;

use app\common\controller\Backend;
use think\Db;

/**
 * 学校列表
 */
class School extends Backend
{

    /**
     * @var \app\common\model\School
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\School;
    }

    /**
     * 查看
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            $params = $this->request->param();

            // 查询数据（带分页）
            $list = $this->model
                ->order($params['sort'] ?? 'id', $params['order'] ?? 'desc')
                ->paginate([
                    'list_rows' => $params['limit'] ?? 10,
                    'page'      => ($params['offset'] / $params['limit'] + 1) ?? 1
                ]);

            // 批量获取所有学校ID
            $schoolIds = array_column($list->items(), 'id');

            // 批量查询学生数量
            $studentCounts = Db::name('user')
                ->where('school_id', 'in', $schoolIds)
                ->where('type', 1)
                ->group('school_id')
                ->column('COUNT(*) as count', 'school_id');

            // 批量查询老师数量
            $teacherCounts = Db::name('user')
                ->where('school_id', 'in', $schoolIds)
                ->where('type', 2)
                ->group('school_id')
                ->column('COUNT(*) as count', 'school_id');

            // 合并数据
            foreach ($list as $key => $item) {
                $list[$key]['student_count'] = $studentCounts[$item['id']] ?? 0;
                $list[$key]['teacher_count'] = $teacherCounts[$item['id']] ?? 0;
            }

            return json([
                "total" => $list->total(),
                "rows"  => $list->items()
            ]);
        }

        return $this->view->fetch();
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post('row/a');
            if (empty($data['name']) || empty($data['avatar'])){
                $this->error('参数不能为空');
            }
            $result = $this->model->save($data);
            if ($result !== false) {
                $this->success('添加成功');
            }
        }
        return parent::add();
    }

    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $data = $this->request->post('row/a');
            if (empty($data['name']) || empty($data['avatar'])){
                $this->error('参数不能为空');
            }
            
            $result = $this->model->where('id', $ids)->update($data);
            if ($result !== false) {
                $this->success('修改成功');
            }
        }
        return parent::edit($ids);
    }
}